import {origin, history} from '../utils/config'
import {message} from 'antd'
import fetch from 'dva/fetch'
import {fetchPost} from "../utils/request";

class auth {
  login(account, verifyCode, cb) {
    cb = arguments[arguments.length - 1]
    if (localStorage.accessToken) {
      if (cb) cb(true)
      this.onChange(true)
      return
    }
    serverLogin(account, verifyCode, (res) => {
      if (res.authenticated) {
        localStorage.accessToken = res.accessToken
        localStorage.userName = account
        if (cb) cb(true)
        this.onChange(true)
        this.getAppList()
        this.getCategoryList()
      } else {
        if (cb) cb(false)
        this.onChange(false)
      }
    })
  }

  getToken() {
    return localStorage.accessToken
  }

  getUserName() {
    return localStorage.userName
  }

  logout(cb) {
    delete localStorage.accessToken
    delete localStorage.userName
    delete sessionStorage.clear()
    if (cb) cb()
    history.push('/login')
    this.onChange(false)
  }

  loggedIn() {
    return localStorage.accessToken
  }

  onChange() {

  }

  // 同：src/components/layout/HeaderNav.js 的getAppList方法
  getAppList() {
    var apps = [{appName: 'qsyq', appCode: '1'}, {appName: 'jyd', appCode: '0'}]
    if (sessionStorage.getItem('appName') == null) {
      sessionStorage.setItem('appName', apps[0].appName)
      sessionStorage.setItem('appCode', apps[0].appCode)
    }
  }

  // 同：src/components/layout/HeaderNav.js 的getCategoryList方法
  getCategoryList() {
    fetchPost('/admin/productCategory/list').then((res) => {
      if (res.code === 0) {
        var data = res.data.list
        if (data.length > 0) {
          if (sessionStorage.getItem('productCategory') == null) {
            sessionStorage.setItem('productCategory', data[0].productCategory)
            sessionStorage.setItem('productCategoryName', data[0].productCategoryName)
          }
        }
      }
    })
  }
}

function serverLogin(account, verifyCode, cb) {
  fetch(`${origin}/admin/login`, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'basicParams': '{\'appClient\': \'web\'}',
    },
    mode: 'cors',
    body: JSON.stringify({
      account,
      verifyCode,
    })
  }).then(res => res.json()).then(json => {
    if (json.code === 0) {
      cb({
        authenticated: true,
        accessToken: json.data.accessToken,
        userName: json.data.userName
      })
    } else {
      cb({
        authenticated: false
      })
      message.error(json.msg)
    }
  })
}

export default new auth()
